/// <reference path="jquery-1.5.1-vsdoc.js" />

/*
 * Async Treeview 0.1 - Lazy-loading extension for Treeview
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 *
 * Copyright (c) 2007 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 *
 */
 
;(function($) {

function load(settings, root, child, container) {

	function createNode(parent) {
    
		var current = $("<li/>").attr("id", this.id || "").html( getImage(this) + "<span>" + this.text + "</span>").appendTo(parent);
        var id = this.id;
        var name = this.text;
        if(this.hasOwnProperty("status"))
        {
           var startAction = $("<a />").appendTo(current);
           var refreshAction = $("<a />").appendTo(current);
           var stopAction = $("<a />").appendTo(current);
           var data =  {packageId: id,serviceFullName: name,rd: Math.random()}
           if( this.isPackage )
                data.serviceFullName= "";
           var $this = this;
           startAction.click( function() {
               current.disabled = true;
               $.ajax({ url: "Package/StartService",
                   dataType: "json",
                   type: "Get",
                   data: data,
                   success: function(data,status)
                   {
                        current.children("img").attr("src","content/images/ajax-loader.gif");
                        updateStatus(current,$this);
                   }
               });
                         
 
           });

           refreshAction.click( function(){  
                current.children("img").attr("src","content/images/ajax-loader.gif");
                updateStatus(current,this);
           });

           stopAction.click(
                function() {
                   current.disabled = true;
                   $.ajax({ url: "Package/StopService",
                       dataType: "json",
                       type: "Get",
                       data:data,
                       success: function(data,status)
                       {
                            updateStatus(current,$this);
                            current.children("img").attr("src","content/images/ajax-loader.gif");
                       }
                   });
                    
           });

           $("<img/>").attr("src","content/images/play.png")
                .attr("title","Start")
                .addClass("icon")
                .appendTo(startAction);
           if( !this.isPackage )
           {
               $("<img/>").attr("src","content/images/repeat.png")
                    .attr("title","Restart")
                    .addClass("icon")
                    .appendTo(refreshAction);
           }
           $("<img/>").attr("src","content/images/stop.png")
                .attr("title","Stop")
                .addClass("icon")
                .appendTo(stopAction);

        }
        
		if (this.classes) {
			current.children("span").addClass(this.classes);
		}
		if (this.expanded) {
			current.addClass("open");
		}
		if (this.hasChildren || this.children && this.children.length) {
			var branch = $("<ul/>").appendTo(current);
			if (this.hasChildren) {
				current.addClass("hasChildren");
				createNode.call({
					classes: "placeholder",
					text: "&nbsp;",
					children:[]
				}, branch);
			}
			if (this.children && this.children.length) {
				$.each(this.children, createNode, [branch])
			}
		} 

        function updateStatus(node,data)
        {
            var id = data.id;
            var name = data.text;
            
            window.setTimeout(function()
            {
                $.ajax({ url: "Package/InfoService",
                dataType: "json",
                type: "Get",
                data: {
                    packageId: id,
                    serviceFullName: name,
                    rd: Math.random()
                },
                success: function(result,status)
                {
                    node.disabled = false;
                    if( !data.isPackage )
                        if( result.length == 1 )
                            node.children("img").attr("src","content/images/" + result[0].status + ".png");
                        else
                            node.children("img").attr("src","content/images/warn.png");
                    else
                         node.children("img").attr("src","content/images/plugin.png");
                }})

            },15000);
        }

        function getImage(obj)
        {
            if( obj.isPackage)
                return ("<img src=\"" +"content/images/plugin.png\" />");
            else if( obj.hasOwnProperty("status") )
                return ("<img src=\"" +"content/images/" + obj.status + ".png\" />");
            else
                return "";
        }
	}
        

	$.ajax($.extend(true, {
		url: settings.url,
		dataType: "json",
		data: {
			id: root,
            rd:Math.random()
		},
		success: function(response) {
			child.empty();
			$.each(response, createNode, [child]);
	        $(container).treeview({add: child});
	    }
	}, settings.ajax));
 
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	if (!settings.url) {
		return proxied.apply(this, arguments);
	}
	var container = this;
	if (!container.children().size())
		load(settings, "0", this, container);
	var userToggle = settings.toggle;
	return proxied.call(this, $.extend({}, settings, {
		collapsed: true,
		toggle: function() {
			var $this = $(this);
			if ($this.hasClass("hasChildren")) {
				var childList = $this.removeClass("hasChildren").find("ul");
				load(settings, this.id, childList, container);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);